package mysql

import "gorm.io/gorm"

type Order struct {
	gorm.Model
	UserId  int64   `gorm:"type:int;not null;index:ip_idx commit:'用户ID'"`
	OrderSn string  `gorm:"type:varchar(50);not null;index:ip_idx commit:'订单号'"`
	Amount  float64 `gorm:"type:decimal(10,2);not null;index:ip_idx commit:'总价'"`
	Status  string  `gorm:"type:enum('已支付','未支付');not null;index:ip_idx commit:'状态'"`
	Payment string  `gorm:"type:enum('微信','支付宝');not null;index:ip_idx commit:'支付方式'"`
}

type OrderGoods struct {
	gorm.Model
	GoodsId   int64   `gorm:"type:int;not null;index:ip_idx commit:'商品ID'"`
	OrderId   int64   `gorm:"type:int;not null;index:ip_idx commit:'订单ID'"`
	Title     string  `gorm:"type:varchar(20);not null;index:ip_idx commit:'房源标题'"`
	Cover     string  `gorm:"type:varchar(255);not null;index:ip_idx commit:'房源封面'"`
	Text      string  `gorm:"type:varchar(50);not null;index:ip_idx commit:'房源描述'"`
	Size      string  `gorm:"type:varchar(36);not null;index:ip_idx commit:'房源规格'"`
	Price     float64 `gorm:"type:decimal(10,2);not null;index:ip_idx commit:'房源价格'"`
	Evaluate  string  `gorm:"type:varchar(36);not null;index:ip_idx commit:'用户评价'"`
	LikeHouse int64   `gorm:"type:int;not null;index:ip_idx commit:'点赞数'"`
	Status    string  `gorm:"type:enum('已上架','未上架');not null;index:ip_idx commit:'房源状态'"`
	Stock     int64   `gorm:"type:int;not null;index:ip_idx commit:'房源库存'"`
}

func CreateAnimals(o *Order, og *OrderGoods) error {
	// 再唠叨一下，事务一旦开始，你就应该使用 tx 处理数据
	tx := DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = tx.Error; err != nil {
		return err
	}

	if err = tx.Create(&o).Error; err != nil {
		tx.Rollback()
		return err
	}

	if err = tx.Create(&og).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
